#!/usr/bin/env ruby

require 'Xml'
require 'Activity'
require 'DataObject'


class Decision < Xml
  ACTIVITY = { :DecisionFunction => "DecisionFunction", :RuleSet => "RuleSet" , :RuleSheet => "RuleSheet" , :Rule => "Rule"}
  
  
  def activity_collect(node)
    act = Activity.new
    act.name = node.xpath("#{node.path}/xmlns:Name")[0].text
    act.type = node.name
    begin
      if act.type == ACTIVITY[:DecisionFunction]
	act.reference = node.xpath("#{node.path}/*/xmlns:Ruleset").collect{|r| r.text}.join(",\n ")
      elsif act.type == ACTIVITY[:RuleSet]
	act.reference = node.xpath("#{node.path}/*[starts-with(local-name(),'Rule')]/xmlns:Name").collect{|r| r.text}.join(",\n ")
      end
    rescue
    end
    begin
    act.operation
    rescue
    end
    begin
      act.input = variables_input(node)
    rescue
    end
    begin
      act.output = variables_output(node)
    rescue
    end
    act.description = documentation(node)
    act
  end

  def activities
    activities_doc.collect do |el|
      activity_collect el
    end
  end

  def activities_doc
    doc.xpath('//*').collect do |el|
      if ACTIVITY.has_value? el.name and !el["id"].nil?
	el
      end
    end.compact
  end

  def documentation(node=nil)
    desc = node.xpath("#{node_path(node)}/xmlns:Description")[0]
    desc = desc.text if !desc.nil?
    desc
  end

  def variables_doc
    @doc.xpath("//xmlns:dataObject")
  end

  def variable_to_data(node)
      var = DataObject.new
      var.name = node.xpath("#{node.path}/xmlns:Alias")[0].text
      var.type = node.xpath("#{node.path}/xmlns:Name")[0].text
      var.namespace = node.xpath("#{node.path}/xmlns:Namespace")[0].text
      var.resource_type = node.name
      var.description
      var
  end

  def variables_input(node)
    var=[]
    node.xpath("#{node.path}/xmlns:DecisionFunctionInput/xmlns:IDofType").each do |name|
	var << variable_by_name(name.text)
    end
    var.uniq.compact
  end

  def variables_output(node)
    var=[]
    node.xpath("#{node.path}/xmlns:DecisionFunctionOutput/xmlns:IDofType").each do |name|
	var << variable_by_name(name.text)
    end
    var.uniq.compact
  end

  def variable_by_name(name)
    variables_collect.select{|v| name.include? v.type}[0]
  end

  def variables_collect
    variables_doc.collect do |el|
      variable_to_data(el)
    end.uniq.compact
  end

  def variables_doc
    @doc.xpath("//xmlns:JaxbFactType")
  end

  def name
    @doc.xpath("//xmlns:Name")[0].text
  end

  def type
    DECISION
  end

end

